import React, { useState, useEffect } from 'react'
import axios from 'axios'
import { Table, Button, Tooltip, Space, message, Popconfirm, Modal, Tree } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';

export default function RoleList() {
    const [dataSource, setDataSource] = useState([])
    // 对话框状态
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 角色框
    const [rolesList, setrolesList] = useState([])
    // 角色权限
    const [currentRights, setcurrentRights] = useState([])
    // 当前ID
    const [currentId, setcurrentId] = useState(0)

    // 请求角色数据
    useEffect(() => {
        axios.get('/roles').then(res => {
            // console.log(res.data);
            setDataSource(res.data)
        })
    }, [])
    // 请求权限数据
    useEffect(() => {
        axios.get('/rights?_embed=children').then(res => {
            setrolesList(res.data)
        })
    },[])
    // 点击确认分配
    const handleOk = () => {
        // console.log(currentRights);
        // console.log(currentId);
        // 同步data
        setDataSource(dataSource.map(item => {
            if(item.id === currentId) {
                return {
                    ...item,
                    rights: currentRights
                }
            } 
            return item
        }))
        axios.patch(`/roles/${currentId}`,{
            rights: currentRights
        })
        setIsModalOpen(false);
        message.success('分配权限成功');
    };
    // 取消分配
    const handleCancel = () => {
        setIsModalOpen(false);
        message.info('已取消分配');
    };
    // 点击复选框触发
    const onCheckChange = (checkKeys) => {
        // console.log(e);
        setcurrentRights(checkKeys.checked)
    }
    // 表格每列分类配置
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Space size="2">
                        <Popconfirm
                            title="删除权限"
                            description="是否永久删除该角色？"
                            onConfirm={() => confirm(item)}
                            onCancel={cancel}
                            okText="确认"
                            cancelText="取消"
                        >
                            <Tooltip title="删除" mouseLeaveDelay={0}>
                                <Button danger shape="circle" icon={<DeleteOutlined />} style={{ marginRight: '10px' }} />
                            </Tooltip>
                        </Popconfirm>
                        <Tooltip title="分配权限" mouseLeaveDelay={0}>
                            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={ () => {
                                setIsModalOpen(true)
                                setcurrentRights(item.rights)
                                setcurrentId(item.id)
                            }} />
                        </Tooltip>
                    </Space>
                </div>
            }
        },
    ];
    // 点击确认删除角色
    const confirm = (item) => {
        setDataSource(dataSource.filter(data => data.id !== item.id))
        axios.delete(`/roles/${item.id}`)
        message.success('删除成功');
    };
    // 取消删除角色
    const cancel = (e) => {
        // console.log(e);
        message.info('已取消删除');
    };
    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 7
            }} rowKey={(item) => item.id} />
            <Modal title="分配权限" open={isModalOpen} onOk={handleOk} okText="确认分配" cancelText="取消分配" onCancel={handleCancel}>
                <Tree
                    defaultExpandAll
                    checkable
                    checkedKeys={currentRights}
                    onCheck={onCheckChange}
                    // checkable 状态下节点选择完全受控（父子节点选中状态不再关联）
                    checkStrictly={true}
                    treeData={rolesList}
                />
            </Modal>
        </div>
    )
}
